/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import dao.BookDao;
import dao.PhotoDao;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;

@WebServlet("/ais")
public class AddImageServlet extends HttpServlet{

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String image="";
        int bookId=Integer.parseInt(req.getParameter("bookid"));
        try {
            image=addDVDinfo(req, resp);
        } catch (SQLException ex) {
            Logger.getLogger(AddBookServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        Boolean bool=new BookDao().addImage(bookId,image);
        resp.setContentType("text/html;charset=utf-8");
        if(bool==false){
            resp.getWriter().println("<script language='javascript'>alert('添加失败！');window.location.href='Admin.jsp';</script>");
        }
        else{
            resp.getWriter().println("<script language='javascript'>alert('封面添加成功！');window.location.href='Admin.jsp';</script>");
        }
        
        
        
    }
    
    
    
    //下面是网上复制的代码
    private static String addDVDinfo(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, ServletException {
        List<String> list = new ArrayList<String>();
        String filename = PhotoDao.getPhotoNewName();
        ServletContext servletContext = null;
        servletContext = request.getSession().getServletContext();
        
        List<FileItem> items = PhotoDao.getRequsetFileItems(request, servletContext);
        boolean isLoadToSQL = false;
        for (FileItem item : items) {
            if (!item.isFormField()) {
             
                if (PhotoDao.isGif(item)) {
                    isLoadToSQL = PhotoDao.saveFile(item, filename);
                } else {
                    System.out.println("后缀格式有误，保存文件失败");
                }
            } else {

                list.add(item.getString("UTF-8"));
            }
        }
        return filename;
    }
    
}
